package com.developer.platform.application.query;

import com.developer.platform.application.query.assembler.UserAssembler;
import com.developer.platform.application.query.dto.CurrUserDto;
import com.developer.platform.application.query.dto.LoginQuery;
import com.developer.platform.domain.security.AuthenticationInfo;
import com.developer.platform.domain.service.IAuthenticationSource;
import com.developer.platform.domain.service.ISecurityService;
import com.developer.platform.domain.service.impl.AuthorizingRealm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
@Component
public class LoginManager {

    private final AuthenticationManager authenticationManager;
    private final IAuthenticationSource authenticationSource;
    private final UserAssembler userAssembler;
    private final ISecurityService securityService;
    private final AuthorizingRealm authorizingRealm;

    public LoginManager(AuthenticationManager authenticationManager,
                        IAuthenticationSource authenticationSource,
                        UserAssembler userAssembler,
                        ISecurityService securityService,
                        AuthorizingRealm authorizingRealm) {
        this.authenticationManager = authenticationManager;
        this.authenticationSource = authenticationSource;
        this.userAssembler = userAssembler;
        this.securityService = securityService;
        this.authorizingRealm = authorizingRealm;
    }

    /**
     *  登录获取token
     *
     * @author ：qiaoliang
     * @param loginQuery : 登录请求模型
     * @return java.lang.String
     * @date 2020-11-09 11:09
     */
    public String login(LoginQuery loginQuery){
        Authentication authenticate = authenticationManager.authenticate(new AuthenticationInfo(loginQuery.getPrincipal(),
                loginQuery.getCredentials(), loginQuery.getLoginType()));
        return authenticationSource.loadGenerateToken(authenticate);
    }


    /**
     *  获取当前登录用户信息
     *
     * @author ：qiaoliang

     * @return com.microorganism.platform.application.query.dto.CurrUserDto
     * @date 2020-10-21 17:23
     */
    public CurrUserDto currUser(){
        return userAssembler.toCurrUserDto(securityService.getUserDetails(),
                authorizingRealm.doGetAuthorizationInfo(securityService.getAuthentication()));
    }

}
